package cn.myjerry.pattern.singleton;

import java.io.ObjectStreamException;
import java.io.Serializable;

/**
 * 测试懒汉式单例模式(如何防止反射或反序列化漏洞)
 * @author Jerry
 *
 */
public class SingletonDemo04 implements Serializable {
	private static final long serialVersionUID = 1L;
	
	private static SingletonDemo04 instance;
	
	private SingletonDemo04() {
		if(instance != null) {
			throw new RuntimeException();
		}
	}
	
	public static synchronized SingletonDemo04 getInstance() {
		if(instance == null) {
			instance = new SingletonDemo04();
		}
		return instance;
	}
	
	// 发序列化时，直接返回此方法指定的对象
	private Object readResolve() throws ObjectStreamException {
		return instance;
	}
}
